package com.lbt.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wzsck.util.Result;
import com.google.gson.Gson;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/json");
		
		PrintWriter out = response.getWriter();
		// 1.创建SmartUpload
		SmartUpload smart = new SmartUpload(); 
		// 2.设置字符集 
		// javaweb 5 
		
		// 3.初始化
		smart.initialize(getServletConfig(), request, response);
		try {
			// 4.上传文件
			smart.upload();
			// 5.保存文件到指定位置(save只提供路径，使用原文件名上传文件) 
			smart.save("/img");
			// 5.保存文件到指定位置(saveAs可以用指定名称上传文件)
			//
			smart.getFiles().getFile(0).saveAs("img/" + System.currentTimeMillis() + ".png"); // 获取文件名
			String filename = smart.getFiles().getFile(0).getFileName();
			Result result = new Result(0, "新图片上传成功", 1, "img/"+filename);
			Gson gson = new Gson();
			String json = gson.toJson(result);
			out.print(json);
		} catch (SmartUploadException e) {
			Result result = new Result(1, "上传失败", 0, "图片过大");
			Gson gson = new Gson();
			String json = gson.toJson(result);
			out.print(json);
			e.printStackTrace();
		}
		out.flush();
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
